package cn.edu.tsinghua.weibo.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.edu.tsinghua.weibo.entity.User;
import cn.edu.tsinghua.weibo.util.DB;
import cn.edu.tsinghua.weibo.util.MD5;

@SuppressWarnings("serial")
public class Login extends HttpServlet {

	private final static String SQL = "select * from user where email=? and password=?";

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		String email = request.getParameter("email");
		String password = MD5.encrypt(request.getParameter("password"));

		try {
			Connection connection = DB.getConnection();
			PreparedStatement preparedStatement;
			preparedStatement = connection.prepareStatement(SQL);
			preparedStatement.setString(1, email);
			preparedStatement.setString(2, password);
			ResultSet resultSet = preparedStatement.executeQuery();

			if (resultSet.next()) {
				User user = new User();
				user.setId(resultSet.getInt("id"));
				user.setAvatar(resultSet.getString("avatar"));
				user.setEmail(resultSet.getString("email"));
				user.setLocation(resultSet.getInt("location"));
				user.setNick(resultSet.getString("nick"));
//				user.setPassword(resultSet.getString("password"));
				user.setSex(resultSet.getInt("sex"));

				HttpSession session = request.getSession();
				session.setAttribute("user", user);
				DB.close(resultSet, preparedStatement, connection);
				response.sendRedirect(Integer.toString(user.getId()));
			} else {
				DB.close(resultSet, preparedStatement, connection);
				request.setAttribute("message", "invalid email or password.");
				request.getRequestDispatcher("index.jsp").forward(request, response);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

}
